import cgi
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import htmltext

class CourseInfo(db.Model):
	id=db.StringProperty()
	email=db.StringProperty()

class Register(webapp.RequestHandler):
	def get(self):
		student=users.get_current_user()	
		if student:
			html=htmltext.full
		
			res=db.GqlQuery("SELECT * FROM CourseInfo WHERE email = '%s'"%student.email())
			existing=[i.id for i in res]
			
			sub=[]
			for i in range(5):
				sub.append("")
				for val in htmltext.allcourses[i]:
					if val in existing:
						sub[i]+="""<input type="checkbox" name="courses" value="%s" CHECKED>%s</input><br>"""%(val,val)
					else:

						sub[i]+="""<input type="checkbox" name="courses" value="%s">%s</input><br>"""%(val,val)

			sub=[users.get_current_user().email(),users.create_logout_url(dest_url=self.request.uri)]+sub			
			html=html%(tuple(sub))
			self.response.out.write(html)
		else:
			auth_url=users.create_login_url(federated_identity="gmail.com",dest_url=self.request.uri)
			subst="""
			In order to choose your courses, you have to <a href="%s">sign in</a> with your google account.
			"""%auth_url
			self.response.out.write(htmltext.basic%subst)

	def post(self):
		student=users.get_current_user()	
		if student:
			courses=self.request.get("courses",allow_multiple=True)
			res=db.GqlQuery("SELECT * FROM CourseInfo WHERE email = '%s'"%student.email())
			existing=[i.id for i in res]
			for course in courses:
				if not course in existing:
					new=CourseInfo()
					new.email=student.email()
					new.id=course
					new.put()
				else:
					pass

			for course in res:
				if not course.id in courses:
					db.delete(course)
				else:
					pass
	

			self.response.out.write("""
			<h2>Registration complete</h2>
			<a href="/register">Modify</a> your details.
			""")
		
		else:

			self.redirect(users.create_login_url(federated_identity="gmail.com",dest_url=self.request.uri))

application = webapp.WSGIApplication([('/register', Register),('/', Register)])

def main():
	run_wsgi_app(application)

if __name__ == "__main__":
	main()

